﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Data;
namespace DAO
{
    public class LoTrinhTuyenDAO : DataProvider
    {
        protected override object GetDataFromDataRow(DataTable dt, int i)
        {


            LoTrinhTuyenDTO objectDTO = new LoTrinhTuyenDTO();
            objectDTO.MaTuyen = int.Parse(dt.Rows[i]["MaTuyen"].ToString());
            objectDTO.STT = int.Parse(dt.Rows[i]["STT"].ToString());
            objectDTO.MaDoan = int.Parse(dt.Rows[i]["MaDoan"].ToString());
            return (object)objectDTO;
        }

        public LoTrinhTuyenDTO[] GetAll()
        {
            String strSQL = "Select * from LoTrinhTuyen ";
            DataTable dt = new DataProvider().ExecuteQuery(strSQL);

            LoTrinhTuyenDTO[] lotrinhtuyenDTOs = new LoTrinhTuyenDTO[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
                lotrinhtuyenDTOs[i] = (LoTrinhTuyenDTO)GetDataFromDataRow(dt, i);

            return lotrinhtuyenDTOs;
        }

        public bool insert(int matuyen, int diadiemdau, int diadiemcuoi)
        {
            DoanDuongDAO ddDAO = new DoanDuongDAO();
            int madoan = ddDAO.insert(diadiemdau, diadiemcuoi);
            int stt = Search_STT(matuyen);
            string insertCommand = "INSERT LoTrinhTuyen(MaTuyen,STT,MaDoan) VALUES(" +
                matuyen + ", " +
                stt + ", " +
                madoan + ")";

            return (ExecuteNonQuery(insertCommand));
        }
        public int Search_STT(int matuyen)
        {
            String strSQL = "Select STT from LoTrinhTuyen where MaTuyen='" + matuyen + "' ";
            DataTable dt = new DataProvider().ExecuteQuery(strSQL);
            if (dt.Rows.Count > 0)
                return int.Parse(dt.Rows[dt.Rows.Count - 1][0].ToString()) + 1;
            else
                return 1;
        }

        public void update(LoTrinhTuyenDTO info)
        {
            string updateCommand = "UPDATE LoTrinhTuyen " +
                                    "SET MaDoan = '" + info.MaDoan + "', " +
                                    " WHERE STT ='" + info.STT + "' AND MaTuyen ='" + info.MaTuyen + "'";


            ExecuteNonQuery(updateCommand);
        }

        public void delete(int matuyen, int stt)
        {
            string deleteCommand = "DELETE FROM LoTrinhTuyen WHERE MaTuyen= " + matuyen + " AND STT=" + stt;
            ExecuteNonQuery(deleteCommand);
        }
    }
}
